#include <iostream>
#include <string>
#include  "PSConsole.hpp" ;
#include <windows.h>

using namespace std;
void SetConsoleTitle(const std::string &title) {
    SetConsoleTitleA(title.c_str());
}


static LRESULT WindowProc(const HWND hwnd,
    UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_CLOSE:
            DestroyWindow(hwnd);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    [[maybe_unused]] PSTR szCmdLine, const int iCmdShow) {


    // 创建控制台窗口
    AllocConsole();
    SetConsoleTitle("Simple Terminal Emulator");
    FILE* fDummy;
    freopen_s(&fDummy, "CONIN$", "r", stdin);
    freopen_s(&fDummy, "CONOUT$", "w", stdout);
    freopen_s(&fDummy, "CONOUT$", "w", stderr);

    u_int result = PowershellConsole();
    if (result != 0) {
        MessageBox(nullptr, "Terminal Error", "Error", MB_OK);
        return 1;
    }

    // 注册窗口类
    WNDCLASS wc = {};
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = "SimpleTerminalEmulator";
    RegisterClass(&wc);

    // 创建窗口
    HWND hwnd = CreateWindow(wc.lpszClassName, "Simple Terminal Emulator",
                             WS_POPUPWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1000, 800 ,
                             NULL, NULL, hInstance, NULL);

    if (hwnd == nullptr) {
        return 0;
    }

    RECT clientRect = {0, 0, 1000, 800};
    AdjustWindowRect(&clientRect, GetWindowLong(hwnd, GWL_STYLE), FALSE);
    SetWindowPos(hwnd, nullptr , 0, 0, clientRect.right - clientRect.left, clientRect.bottom - clientRect.top, SWP_NOMOVE | SWP_NOZORDER);

    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    MSG msg = {};
    while (GetMessage(&msg, nullptr, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}